mui.init({
	keyEventBind: {
		backbutton: false, //Boolean(默认true)关闭back按键监听,防止回到登录页面
	},
});

mui.plusReady(function() {
	firstPageLoad();
	
	var _self;
	plusReady();
	function plusReady() {
		_self = plus.webview.currentWebview();
		_self.setPullToRefresh({
			support: true,
			height: '50px',
			range: '100px',
			style: 'circle',
			offset: '1px'
		}, pulldownRefresh);
		
		
		//跳转页面
		[].slice.call( document.querySelectorAll('*[data-url]') ).forEach(function(e) {
			e.addEventListener("tap", function() {
				var url = this.getAttribute("data-url");
				mui.openWindow(url, {});
			});
		});
		
	}
	function pulldownRefresh() {
		setTimeout(function() {
			equipmentPageRefresh(_self);
		}, 500);
	}
});

//加载本地数据
function loadLocalData(){
	var storage = plus.storage;
	//banner图
	var imageUrlsStorage = storage.getItem("equipment_banner_image_urls");
	if(imageUrlsStorage) {
		renderBanner(JSON.parse(imageUrlsStorage));
	}
	
	//待操作数据
	var confirmInfo = storage.getItem("equipment_wait_to_confirm_info");
	if(confirmInfo) {
		renderWaitToConfirmInfo(JSON.parse(confirmInfo));
	}
	
	//工单数据
	var chartData = storage.getItem("homepage_line_chart_data");
	if(chartData) {
		drawLineChart(JSON.parse(chartData));
	}
	
	//设备推荐数据
	var recommendEquipment = storage.getItem("recommend_equipment_list");
	if (recommendEquipment) {
		var data = JSON.parse(recommendEquipment);
		renderRecommendEquipment(data);
	}
	
	//方法推荐数据
	var recoveryMessage = storage.getItem("recoveryMessageData_equipment");
	if (recoveryMessage) {
		var data = JSON.parse(recoveryMessage);
		renderRecoveryMessage(data);
	}
	
}

//首屏数据加载
function firstPageLoad() {
	// 确保首屏加载时能马上展示内容
	loadLocalData();
	
	if(plus.networkinfo.getCurrentType() === 1) {
		mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
		return false;
	}
	
	
	var storage = plus.storage,
		urlPrefix = urlPrefix = "https://bird.ioliu.cn/v1?url=",
		bannerComplete = waitToConfirmComplete = lineChartComplete = recommendEquipmentComplete = recoveryMessageComplete = false,
		mainBtn = document.querySelectorAll(".main-btn a");
	
	
	// 请求设备页面banner图信息
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=equipment&a=getBannerList&hospitalid=10&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {			
			if(textStatus === "success") {
				var data = data.data;				
				if(data.length) {
					renderBanner(data);
					storage.setItem("equipment_banner_image_urls", JSON.stringify(data));
				}
				bannerComplete = true;
				stopFirstPageLoading();
			}
		}
	});
	
	
	// 请求待确认信息
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=statistic&a=getOrderStateStatInfo&factoryid=10&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data;
				renderWaitToConfirmInfo(data);
				storage.setItem("equipment_wait_to_confirm_info", JSON.stringify(data));
				waitToConfirmComplete = true;
				stopFirstPageLoading();
			}
		}
	});
	
	// 请求折线图数据
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=statistic&a=getWorkOrderStatInfo&factoryid=10&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				drawLineChart(data);
				storage.setItem("homepage_line_chart_data", JSON.stringify(data));
				lineChartComplete = true;
				stopFirstPageLoading();
			}
		}
	});

	// 请求推荐设备数据
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getRecommendEquipmentList&hospitalid=10&departmentid=11&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data;
				if(data.length) {
					renderRecommendEquipment(data);
					storage.setItem("recommend_equipment_list", JSON.stringify(data));
				}
				recommendEquipmentComplete = true;
				stopFirstPageLoading();
			}
		}
	});
	
	// 请求设备故障排除方法
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getRecommendRepairNoteList&hospitalid=10&departmentid=11&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {			
			if(textStatus === "success") {
				var data = data.data;
				if(data.length) {
					renderRecoveryMessage(data);
					storage.setItem("recoveryMessageData_equipment", JSON.stringify(data));
				}
				recoveryMessageComplete = true;
				stopFirstPageLoading();
			}
		}
	});
	
	function stopFirstPageLoading() {
		if(bannerComplete && waitToConfirmComplete && lineChartComplete && recommendEquipmentComplete && recoveryMessageComplete) {
			mui.toast("刷新成功！");
		}
	}
}




function equipmentPageRefresh(that) {

	if(plus.networkinfo.getCurrentType() === 1) {
		loadLocalData();
		that.endPullToRefresh();
		mui.toast("好像没有网络了~");
		return;//断网则结束
	}
		
	var storage = plus.storage,
		urlPrefix = urlPrefix = "https://bird.ioliu.cn/v1?url=",
		bannerComplete = waitToConfirmComplete = lineChartComplete = recommendEquipmentComplete = recoveryMessageComplete = false,
		mainBtn = document.querySelectorAll(".main-btn a");
	
	// 请求设备页面banner图信息
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=equipment&a=getBannerList&hospitalid=10&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data;
				if(data.length) {
					renderBanner(data);
					storage.setItem("equipment_banner_image_urls", JSON.stringify(data));
				}
				bannerComplete = true;
				stopPullDownRefresh(that);
			}
		}
	});
	
	
	// 请求待确认信息
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=statistic&a=getOrderStateStatInfo&factoryid=10&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data;
				renderWaitToConfirmInfo(data);
				storage.setItem("equipment_wait_to_confirm_info", JSON.stringify(data));
				waitToConfirmComplete = true;
				stopPullDownRefresh(that);
			}
		}
	});
	
	// 请求折线图数据
	mui.ajax(urlPrefix + "http://hospital.xiaoweicanting.com/factory.php?m=App&c=statistic&a=getWorkOrderStatInfo&factoryid=10&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				drawLineChart(data);
				storage.setItem("homepage_line_chart_data", JSON.stringify(data));
				lineChartComplete = true;
				stopPullDownRefresh(that);
			}
		}
	});
	
	
	// 请求推荐设备数据
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getRecommendEquipmentList&hospitalid=10&departmentid=11&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data;
				if(data.length) {
					renderRecommendEquipment(data);
					storage.setItem("recommend_equipment_list", JSON.stringify(data));
				}
				recommendEquipmentComplete = true;
				stopPullDownRefresh(that);
			}
		}
	});
	
	// 请求设备故障排除方法
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getRecommendRepairNoteList&hospitalid=10&departmentid=11&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {			
			if(textStatus === "success") {
				var data = data.data;
				if(data.length) {
					renderRecoveryMessage(data);
					storage.setItem("recoveryMessageData_equipment", JSON.stringify(data));
				}
				recoveryMessageComplete = true;
				stopPullDownRefresh(that);
			}
		}
	});
	
	function stopPullDownRefresh(that) {
		if(that && bannerComplete && waitToConfirmComplete && lineChartComplete && recommendEquipmentComplete && recoveryMessageComplete) {
			that.endPullToRefresh();
			mui.toast("刷新成功！");
		}
	}
}

function renderBanner(data) {
	var sliderGroup = document.getElementById("slider-group"),
		storage = plus.storage;
	// 如果请求到的数据与本地缓存数据相同并且页面是二次刷新，则直接返回，防止页面闪烁
	// 页面闪烁的根源在于渲染banner时直接替换元素的innerHTML属性值。
	if(JSON.stringify(data) === storage.getItem("equipment_banner_image_urls") && sliderGroup.querySelector(".mui-slider-item")) return;

	var length = data.length,
		sliderIndicators = document.getElementById("slider-indicator"),
		rootPath = "http://hospital.xiaoweicanting.com/",
		itemHtml = itemFragment = indicatorHtml = indicatorFragment = "";
	
	for(var i = 0; i < length; i++) {
		itemFragment = '<div class="mui-slider-item" title="' + data[i].url + '">' + 
							'<a href="#" style="height: 150px;">' + 
								'<img src="../../images/test/timg.jpeg" data-src="' + rootPath + data[i].pic + '" onload="load(this)">' + 
							'</a>' + 
						'</div>';
		if (i === 0) {
			itemHtml += itemFragment.replace("mui-slider-item", "mui-slider-item mui-slider-item-duplicate") + itemFragment;
		} else if (i === length - 1) {
			itemHtml += itemFragment + itemFragment.replace("mui-slider-item", "mui-slider-item mui-slider-item-duplicate");
		} else {
			itemHtml += itemFragment;
		}

		// 创建轮播图底部的指示器
		indicatorFragment = '<div class="mui-indicator"></div>';
		if (i === 0) {
			indicatorHtml += indicatorFragment.replace("mui-indicator", "mui-indicator mui-active");
		} else {
			indicatorHtml += indicatorFragment;
		}
	}
	sliderGroup.innerHTML = itemHtml;
	sliderIndicators.innerHTML = indicatorHtml;
	mui(".mui-slider-group").on('tap', '.mui-slider-item', function(){
		var title = this.getAttribute("title");
		mui.openWindow({
			url: "../homepage/hpPicUrl.html",
		    id: "hpPicUrl.html",
		    styles:{
			    	top: 0,
			    	bottom: 0
		    },
		    extras:{
		    		url: title
		    }
		});
	});
	var gallery = mui('.mui-slider');
	gallery.slider({
		interval: 0
	});
}

function renderWaitToConfirmInfo(data) {
	var textNodes = document.querySelectorAll(".wait-to-confirm-count");
	for(var i = 0; i < 3; i++) {
		textNodes[i].innerHTML = data[i].number;
	}
	
	document.getElementById("tab1").addEventListener("tap", function() {
			mui.openWindow('../equipment/equipment_manage.html', '../equipment/equipment_manage.html', {styles:{
				scrollIndicator: 'none'
			}});
		});
	document.getElementById("tab2").addEventListener("tap", function() {
			mui.openWindow('../fault/management.html', '../fault/management.html', {styles:{
				scrollIndicator: 'none'
			}});
		});
	document.getElementById("tab3").addEventListener("tap", function() {
			mui.openWindow('../order/order_with_back.html', '../order/order_with_back.html', {styles:{
				scrollIndicator: 'none'
			}});
	});
	
	document.getElementById("tab4").addEventListener("tap", function() {
			mui.openWindow('../equipment/barcode.html', '../equipment/barcode.html', {styles:{
				scrollIndicator: 'none'
			}});
	});
}

function drawLineChart(data) {	
	var ctx = document.getElementById("equipmentChart");
	var myMingxiChart = new Chart(ctx, {
	    type: 'line',
	    data: {
		    labels: data.xdata,
		    datasets: [
		        {
		            label: "工单数量",
		            fill: true,
		            lineTension: 0.4,
		            backgroundColor: "rgba(75,192,192,0.4)",
		            borderColor: "rgba(75,192,192,1)",
		            borderCapStyle: 'butt',
		            borderDash: [],
		            borderDashOffset: 0.0,
		            borderJoinStyle: 'miter',
		            pointBorderColor: "rgba(75,192,192,1)",
		            pointBackgroundColor: "#fff",
		            pointBorderWidth: 1,
		            pointHoverRadius: 5,
		            pointHoverBackgroundColor: "rgba(75,192,192,1)",
		            pointHoverBorderColor: "rgba(220,220,220,1)",
		            pointHoverBorderWidth: 2,
		            pointRadius: 1,
		            pointHitRadius: 10,
		            data: data.ydata,
		            spanGaps: false,
		        }
		    ]
		}
	});
}

function renderRecommendEquipment(data) {
	var html = "<ul class='mui-table-view'>",
		rootPath = "http://app.xiaoweicanting.com/",
		//rootPath = "",
		recommendEquipment = document.querySelector(".recommend-equipment-content"),
		pics;
	for(var i = 0, length = data.length; i < length; i++) {
		pics = data[i].pics;
		html += "<li class='mui-table-view-cell' data-url='" + data[i].url + "'>";
		if(pics && pics[0]) {
			html += "<h5 class='title'>" + data[i].title + "</h5><div class='equipment-img-container'>";
			for(var j = 0, len = pics.length; j < len; j++) {
				html += "<img src='../../images/test/timg.jpeg' data-src='" + rootPath + pics[j] + "' onload='load(this)' class='recommend-equipment-img' />";
			}
			html += "</div>";
		} else {
			html += "<h5 class='title'>" + data[i].title + "</h5><p class='equipment-text-content'>" + data[i].content + "</p>";
		}
		html += "</li>";
	}
	recommendEquipment.innerHTML = html;
	[].slice.call(document.querySelectorAll(".recommend-equipment-content li")).forEach(function(v) {
		v.addEventListener("tap", function() {
			mui.openWindow({
				url: "../homepage/hpPicUrl.html",
			    id: "hpPicUrl.html",
			    styles:{
			    	top: 0,
			    	bottom: 0
			    },
			    extras:{
			    	url: this.getAttribute("data-url")
			    }
			});
		});
	})
}

function renderRecoveryMessage(data) {
	var messageList = document.querySelector(".recovery-content"),
		html = '<ul class="mui-table-view">';
	for(var i = 0, length = data.length; i < length; i++) {
		html += '<li class="mui-table-view-cell" data-url="http://www.baidu.com/">' + 
					'<h5>' + data[i].title + '</h5>' + 
					'<p class="recovery-methods-addtime">' + data[i].addtime + '</p>' + 
				'</li>';
	}
	html += "</ul>";
	messageList.innerHTML = html;
	[].slice.call(messageList.querySelectorAll("li")).forEach(function(v) {
		v.addEventListener("tap", function() {
			mui.openWindow({
				url: "../homepage/hpPicUrl.html",
			    id: "hpPicUrl.html",
			    styles:{
			    	top: 0,
			    	bottom: 0
			    },
			    extras:{
			    	url: this.getAttribute("data-url")
			    }
			});
		}, false);
	});
}